package com.kamistoat.meimeimall.common.annotation.annotationHandler;

import com.kamistoat.meimeimall.common.annotation.LoginRequired;
import com.kamistoat.meimeimall.common.constant.AuthConstant;
import com.kamistoat.meimeimall.common.exception.BizCodeEnum;
import com.kamistoat.meimeimall.common.threadlocal.ThreadLocalContextHolder;
import com.kamistoat.meimeimall.common.utils.R;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * {@link com.kamistoat.meimeimall.common.annotation.LoginRequired} 注解的处理器。
 * 做强制登录验证。要求ThreadLocal中必须存在用户登录令牌
 * <p></p>
 * 顺序-50，比全局登录拦截器 {@link com.kamistoat.meimeimall.common.interceptor.GlobalLoginInterceptor} 级别低.
 */
@Aspect
@Component
@Order(-50)
public class LoginRequiredHandler {
    @Around(value = "@annotation(loginRequired)")
    public R innerAround(ProceedingJoinPoint proceedingJoinPoint, LoginRequired loginRequired) throws Throwable {
        // 检验 ThreadLocal 中是否存在登录令牌
        String loginSuccessToString = (String) ThreadLocalContextHolder.get(AuthConstant.LOGIN_USER_THREADLOCAL_NAME);
        if(StringUtils.isEmpty(loginSuccessToString)){
            return R.error(BizCodeEnum.NEED_LOGIN.getCode(), BizCodeEnum.NEED_LOGIN.getMessage());
        }
        return (R) proceedingJoinPoint.proceed();
    }
}
